<template>
  <div class="file-uploader" @dragover.prevent @drop="handleDrop">
    <!-- 文件输入 -->
    <input type="file" multiple ref="fileInput" @change="handleFileChange" />

    <!-- 触发区域 -->
    <div class="upload-area" @click="$refs.fileInput.click()">
      点击上传 / 拖放文件到这里
    </div>

    <!-- 已选文件列表 -->
    <ul v-if="selectedFiles.length" class="file-list">
      <li v-for="(file, index) in selectedFiles" :key="index">
        {{ file.name }} ({{ formatSize(file.size) }})
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const emit = defineEmits(['upload']) // 定义 upload 事件用于向外传递文件

const fileInput = ref<HTMLInputElement | null>(null)
const selectedFiles = ref<File[]>([])

// 格式化大小
function formatSize(size: number): string {
  if (size < 1024) return size + ' B'
  else if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
  else return (size / (1024 * 1024)).toFixed(1) + ' MB'
}

// 处理文件选择
function handleFileChange(event: Event) {
  const files = (event.target as HTMLInputElement).files
  if (files && files.length > 0) {
    const newFiles = Array.from(files)
    selectedFiles.value.push(...newFiles)
    emit('upload', { files: newFiles })
  }
}

// 处理拖拽上传
function handleDrop(event: DragEvent) {
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    const newFiles = Array.from(files)
    selectedFiles.value.push(...newFiles)
    emit('upload', { files: newFiles })
  }
}

// 监听粘贴上传
document.addEventListener('paste', (e) => {
  const items = e.clipboardData?.items
  if (!items) return

  const files: File[] = []

  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    if (item.kind === 'file') {
      const file = item.getAsFile()
      if (file) files.push(file)
    }
  }

  if (files.length > 0) {
    selectedFiles.value.push(...files)
    emit('upload', { files })
  }
})
</script>

<style scoped>
.file-uploader {
  border: 2px dashed #ccc;
  padding: 20px;
  text-align: center;

  .upload-area {
    cursor: pointer;
    color: #1890ff;
    font-weight: bold;
  }

  input[type="file"] {
    display: none;
  }

  ul.file-list {
    margin-top: 10px;
    list-style: none;
    padding-left: 0;

    li {
      margin: 5px 0;
      font-size: 14px;
    }
  }
}
</style>